<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use App\V3\V3_2_7\Models\StorageShelfModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShelfService
{
    public static function get_list_by_main_id($main_id, $data)
    {
        $list = StorageShelfModel::select(
            'id',
            'shelf_name',
            'shelf_type',
        )
            ->where([
                'status' => StorageShelfModel::USEDSTATUS,
                'main_id' => $main_id,
                'storage_id' => $data['storageId']
            ])
            ->with('locations', function ($query) {
                $query->select(
                    'id',
                    'location_name',
                    'shelf_id',
                    'storage_id'
                )->where([
                    'status' => StorageShelfLocationModel::USEDSTATUS
                ]);
            })
            ->orderBy('id', 'desc')->get()->toArray();

        return $list;
    }

    //用于删除功能判断库存信息 返回1 可以删除 0不能删除
    public static function judging_del($id, $id_type, $main_id)
    {
        $res = StorageManageModel::select('*')->where('delete_flag', 0);
        switch ($id_type) {
            case 1: //删除仓库使用
                $res = $res->where('storage_id', $id);
                break;
            case 2: //删除货架使用
                $res = $res->where('shelf_id', $id);

                break;
            case 3: //删除库位使用
                $res = $res->where('location_id', $id);
                break;
            default:
                $res = $res->where('storage_id', $id);
        }
        $res = $res->where('main_id', $main_id);

        $res = $res->where('in_storage_num', '!=', 0)->first();

        if (empty($res)) {
            return 1;
        } else {
            return 0;
        }
    }

    //创建货架和库位
    public static function create_default_shelf_location($storage_id, $main_id, $type = 1, $shelf_name = '默认货架', $location_name = '默认库位')
    {
        DB::beginTransaction();

        try {
            $shelf_obj = StorageShelfModel::updateOrCreate([
                'storage_id' => $storage_id,
                'main_id' => $main_id,
                'status' => StorageShelfModel::USEDSTATUS,

            ], [
                'shelf_name' => $shelf_name,
                'main_id' => $main_id,
                'storage_id' => $storage_id,
                'status' => StorageShelfModel::USEDSTATUS,
                'shelf_type' => $type,
            ]);

            $shelf_id = $shelf_obj->id;
            $location_obj = StorageShelfLocationModel::updateOrCreate([
                'storage_id' => $storage_id,
                'main_id' => $main_id,
                'shelf_id' => $shelf_id,
                'status' => StorageShelfModel::USEDSTATUS

            ], [
                'location_name' => $location_name,
                'main_id' => $main_id,
                'storage_id' => $storage_id,
                'shelf_id' => $shelf_id,
                'status' => StorageShelfModel::USEDSTATUS,
                'shelf_type' => $type,

            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }

    //判断是否开启货架功能
    public static function is_use_shelf($main_id)
    {
        $info = AdminAddendumModel::select('*')->where(['main_id' => $main_id])->first();
        if (empty($info['is_use_shelf'])) {
            return 0;
        } else {
            return 1;
        }
    }

    //获取默认货架和库位
    public static function get_default($id, $type = 1)
    {
        if ($type == 1) {
            //获取默认货架
            $data = StorageShelfModel::select(
                'id',
                'shelf_name',
            )->where([
                'status' => StorageShelfModel::USEDSTATUS,
                'storage_id' => $id,
                'shelf_type' => StorageShelfModel::DEFAULTTYPE,
            ])->orderBy('id', 'asc')
                ->first();
        } else {
            //获取库位
            $data = StorageShelfLocationModel::select(
                'id',
                'location_name',
            )->where([
                'status' => StorageShelfLocationModel::USEDSTATUS,
                'shelf_id' => $id,
                'location_type' => StorageShelfLocationModel::DEFAULTTYPE,
            ])->orderBy('id', 'asc')
                ->first();
        }

        return $data;
    }

    public static function shelf_list($main_id, $data)
    {
        $list = StorageShelfModel::select(
            'id',
            'shelf_name',
            'shelf_type',
            'sort',
            'remark'
        )->where([
            'status' => StorageShelfModel::USEDSTATUS,
            'storage_id' => $data['storageId'],
            'main_id' => $main_id,
        ]);

        if (!empty($data['searchData'])) {
            $list = $list->where('shelf_name', 'LIKE', "%{$data['searchData']}%");
        }
        $list = $list->orderBy('shelf_type', 'ASC')
            ->orderBy('sort', 'ASC')
            ->get();
        if (!empty($list->toArray())) {
            $list = $list->toArray();
            foreach ($list as &$val) {
                $val['standard_num'] = StorageShelfLocationModel::query()
                    ->where([
                        'status' => 1,
                        'shelf_id' => $val['id']
                    ])->sum("standard_num") ?? 0;
                $val['total_num'] = StorageManageModel::query()
                    ->where([
                        'delete_flag' => 0,
                        'main_id' => $main_id,
                        'shelf_id' => $val['id'],
                        'storage_id' => $data['storageId'],
                    ])->sum('in_storage_num');
            }
        }
        return $list;
    }

    public static function location_list($main_id, $data)
    {
        $list = StorageShelfLocationModel::select(
            'id',
            'location_name',
            'location_type',
            'storage_id',
            'shelf_id',
            'sort',
            'remark',
            'standard_num'
        )->where([
            'status' => StorageShelfLocationModel::USEDSTATUS,
            'shelf_id' => $data['shelfId'],
            'main_id' => $main_id,
        ]);

        if (!empty($data['searchData'])) {
            $list = $list->where('location_name', 'LIKE', "%{$data['searchData']}%");
        }

        $list = $list->orderBy('sort', 'ASC')
            ->orderBy('location_type', 'ASC')->get()->toArray();

        foreach ($list as &$v) {
            $storageManageInfo = StorageManageModel::query()
                ->select(
                    'id',
                    DB::raw('SUM(in_storage_num) as total_num')
                )->where([
                    'storage_id' => $v['storage_id'],
                    'shelf_id' => $v['shelf_id'],
                    'location_id' => $v['id'],
                ])->first();

            unset($v['shelf_id']);
            unset($v['storage_id']);
            $v['total_num'] = $storageManageInfo['total_num'];
            $v['is_null'] = empty($storageManageInfo['id']) ? 1 : 0;
        }

        return $list;
    }

    public static function shelfLocationAdd($data): ?array
    {
        $shelfLocationArr = json_decode($data['shelf_location_data'], true);
        $inData = [];
        $i = 0;
        $j = 0;
        DB::beginTransaction();
        try {
            foreach ($shelfLocationArr as $key => $val) {
                if (empty($val['name']))
                    throw new \Exception('货架库位名称必填！');
                $result = [
                    'main_id' => $data['main_id'],
                    'storage_id' => $data['storage_id'],
                    'sort' => $val['sort'] ?? '',
                    'remark' => $val['remark'] ?? '',
                    'created_at' => $data['time']
                ];

                if (!empty($data['shelf_id'])) {//创建库位
                    /*if (StorageShelfLocationModel::query()->where([
                        'status' => 1,
                        'main_id' => $data['main_id'],
                        'location_name' => $val['name'],
                        'storage_id' => $data['storage_id'],
                        //'shelf_id' => $data['shelf_id']
                    ])->exists()) {
                        throw new \Exception('库位名称：' . $val['name'] . '，名称重复，请重新创建！');
                    }*/
                    if (isset($val['standard_num']))
                        $result['standard_num'] = $val['standard_num'];
                    $result['log_no'] = getNO('storage_shelf_location', 'log_no');
                    $result['location_type'] = 2;
                    $result['shelf_id'] = $data['shelf_id'];
                    $result['location_name'] = $val['name'] ?? '';
                    if (!StorageShelfLocationModel::query()->where([
                        'status' => 1,
                        'main_id' => $data['main_id'],
                        //'shelf_id' => $data['shelf_id'],
                        'storage_id' => $data['storage_id']])
                        ->exists()) {
                        if ($j === 0) {
                            $result['location_type'] = 1;
                        }
                        $j++;
                    }

                } else {//创建货架
                    $result['shelf_type'] = 2;
                    $result['shelf_name'] = $val['name'] ?? '';
                    /*if (StorageShelfModel::query()->where([
                        'status' => 1,
                        'main_id' => $data['main_id'],
                        'shelf_name' => $val['name'],
                        'storage_id' => $data['storage_id']
                    ])->exists()) {
                        throw new \Exception('货架：' . $val['name'] . '，名称重复，请重新创建！');
                    }*/
                    if (!StorageShelfModel::query()->where([
                        'status' => 1,
                        'main_id' => $data['main_id'],
                        'storage_id' => $data['storage_id']])
                        ->exists()) {
                        if ($i === 0) {
                            $result['shelf_type'] = 1;
                        }
                        $i++;
                    }
                }
                $inData[] = $result;
            }

            if (!empty($data['shelf_id'])) {
                StorageShelfLocationModel::query()->insert($inData);
            } else {
                StorageShelfModel::query()->insert($inData);
            }
            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('批量创建货架库位' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    /**
     *设置默认货架与库位
     * Author: zlf
     * Created at 2024/8/10 16:53
     * @param $data
     * @return JsonResponse|null
     */
    public static function setDefaultShelfLocation($data): ?JsonResponse
    {
        $defInfo = [];
        DB::beginTransaction();
        try {
            if ((int)$data['type'] === 1) {
                $defInfo = StorageShelfLocationModel::query()->where([
                    'storage_id' => $data['storage_id'],
                    'shelf_id' => $data['shelf_id'],
                    'status' => 1,
                    'location_type' => 1,
                    'main_id' => $data['main_id']
                ])->first();
                StorageShelfLocationModel::query()->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->update(['location_type' => 1]);
                if (!empty($defInfo))
                    $defInfo->location_type = 2;
            } else {
                $defInfo = StorageShelfModel::query()->where([
                    'status' => 1,
                    'shelf_type' => 1,
                    'main_id' => $data['main_id'],
                    'storage_id' => $data['storage_id'],
                ])->first();
                StorageShelfModel::query()->where([
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->update(['shelf_type' => 1]);
                if (!empty($defInfo))
                    $defInfo->shelf_type = 2;
            }
            if (!empty($defInfo)) {
                $defInfo->save();
            }
            CommonService::operateResult(
                $data['user_id'],
                $data['time'],
                $data,
                '设置成功！'
            );
            DB::commit();
            return success();
        } catch (\Exception $e) {
            Log::debug('设置默认货架或货架异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }
}
